Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

424
Visualizações
How to Replace null with "-" using single line in Jquery

How to Replace null with - using single line in jQuery

For Example

    var obj={
        "Key1":null,
        "key2":"I have null",
        "key3":null

    }

Expected Output:

var obj={
    "Key1":"-",
    "key2":"I have null",
    "key3":"-"

}
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You could use Object.keys and check the value. with a recursive function with a closure over the iterating object.

var iter = o => k => o[k] && typeof o[k] === 'object' && Object.keys(o[k]).forEach(iter(o[k])) || o[k] === null && (o[k] = '-'),
    object = { Key1: null, key2: "I have null", key3: { kje: "test", dfasfd: null, demo: "null demo" } }; 

Object.keys(object).forEach(iter(object));
console.log(object);

which basically resolves with ES5 in

var object = { Key1: null, key2: "I have null", key3: { kje: "test", dfasfd: null, demo: "null demo" } }; 

Object.keys(object).forEach(function iter(o) {
    return function (k) {
        if (o[k] && typeof o[k] === 'object') {
            Object.keys(o[k]).forEach(iter(o[k]));
            return;
        }
        o[k] === null && (o[k] = '-');
    };
}(object));
console.log(object);

about 4 years ago · Santiago Trujillo Relatório

0

This one-line function will work:

function nullToDash(obj){for(e in obj){if(obj.hasOwnProperty(e) && obj[e]===null){obj[e]="-";}}}

Edit: Unminified above function for better understanding

function nullToDash(obj){
    for(e in obj){
        if(obj.hasOwnProperty(e) && obj[e]===null){
            obj[e]="-";
        }
    }
}
about 4 years ago · Santiago Trujillo Relatório

0

In one line, It would look something like

JSON.parse(JSON.stringify(obj).split(":null").join((':\"-"')));

var obj = {
  "Key1": null,
  "key2": "I have null",
  "key3": null
}

var obj1=JSON.parse(JSON.stringify(obj).split(":null").join((':\"-"')));

console.log(obj1)

To make the code generic

$.each( obj, function( key, value ) {
 if (value == null) 
   value = "-";
});
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda